﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using MvcCodefirstDemo.Models;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace MvcCodefirstDemo.DAL
{
    public class SchoolContext : DbContext
    {
        public SchoolContext() : base("SchoolContext")
        { }

        /*In Entity Framework terminology, an entity set typically corresponds to a database table, and an entity corresponds to a row in the table.
         在ef中，一个entity set代表数据库的一个表，一个entity代表一个表的一行
        */
        public DbSet<Student> Students { get; set; }
        public DbSet<Department> Departments { get; set; }
        public DbSet<Enrollment> Enrollments { get; set; }
        public DbSet<Course> Courses { get; set; }
        public DbSet<Instructor> Instructors { get; set; }
        public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
        public DbSet<Person> People { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //prevents table names from being pluralized(防止生成的数据库表名称是复数形式，如Students，Enrollments，Courses)
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Entity<Course>()
             .HasMany(c => c.Instructors).WithMany(i => i.Courses)
             .Map(t => t.MapLeftKey("CourseID")
                 .MapRightKey("InstructorID")
                 .ToTable("CourseInstructor"));

            modelBuilder.Entity<Department>().MapToStoredProcedures();

            modelBuilder.Entity<Department>().Property(p => p.RowVersion).IsConcurrencyToken();
        }
    }
}